import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '@/store'

import {
  default_routes,
  all_routes,
  error_routes
} from './routes'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes: default_routes
})

setRoutes()
function setRoutes() {
  try {
    const menuList = JSON.parse(sessionStorage.getItem('MENU_LIST'))
    if((menuList ?? '') !== '' && menuList.length !== 0) {
      const routeUrlList = menuList.map(item => item.routeUrl)
  
      const routes = all_routes.filter(item => {
        return routeUrlList.includes(item.name)
      })
  
      routes.forEach(route => {
        router.addRoute('Main', route)
      })

      error_routes.forEach(route => {
        router.addRoute(route)
      })

      console.log('所有已配置路由', router.getRoutes())

    } else {
      console.warn('此用户没有菜单')
    }
  } catch (err) {
    console.error(err)
  }


}

router.beforeEach(async (to, from ,next) => {
    
  /* 取消上一页面的所有请求 */ 
  // store.dispatch('request/cancelAllRequest', true)



  /* 进入登录页面，清除用户信息 */
  if(to.name === 'Login') {
    sessionStorage.clear()
  }
  
  /* 面包屑路由处理 */
  const target_route = all_routes.find(item => item.name == to.name)
  store.commit('breadcrumb/SET_CURRENT_BREADCRUMB', target_route?.meta?.breadcrumb)

  
  next()
})

export default router

